"""
python3 check_data.py -t "10:30:0"

python3 check_data.py -dt '2022-6-1 10:34:0'
"""
import psycopg2
from datetime import datetime, timedelta
import argparse
DBCONFIG = {
    "dbname": "orthanc",
    "user": "postgres",
    "password": "biomind",
    "host": "127.0.0.1",
    "port": "5432"
}


class PostgresqlUtils():
    def __init__(self):
        try:
            self.conn = psycopg2.connect(
                database=DBCONFIG["dbname"],
                user=DBCONFIG["user"],
                password=DBCONFIG["password"],
                host=DBCONFIG["host"],
                port=DBCONFIG["port"]
            )
            self.cursor = self.conn.cursor()
        except Exception as e:
            print("failed to connect to postgresql: {0}".format(e))

    def __del__(self):
        print("\nrelease postgresql connection")
        self.cursor.close()
        self.conn.close()

    def select(self, sql):
        # print("PostgresqlUtils::select: [{0}]".format(sql))
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def upsert(self, sql):
        # print ("PostgresqlUtils::upsert: [{0}]".format(sql))
        self.cursor.execute(sql)
        self.conn.commit()


POSTGRESQLUTILS = PostgresqlUtils()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Update Biomind Model Repository")
    parser.add_argument(
        "-dt",
        "--datetime",
        type=str,
        required=False,
        default='',
        help='datetime, format:Y-m-d H:M:S, e.g. 2022-06-07 10:34:00, if no set default to thirty minites ago')
    parser.add_argument(
        '-t',
        "--time",
        type=str,
        required=False,
        default='',
        help='time, format: H:M:S, e.g. 10:34:00, if no set default to thirty minites ago'
    )
    args = parser.parse_args()
    start_time = ''
    try:
        if args.datetime:
            start_time = args.datetime
        elif args.time:
            time = datetime.strptime(args.time, "%H:%M:%S")
            today = datetime.today()
            start_time = time.replace(year=today.year, month=today.month, day=today.day).strftime("%Y-%m-%d %H:%M:%S")
    except BaseException as err:
        print(err)
    if not start_time:
        start_time = (datetime.now() - timedelta(minutes=30)).strftime('%Y-%m-%d %H:%M:%S')
    print(f'start_time is set to {start_time}')
    sql = '''select patientid,patientname,accessionnumber from study where lastbuilddatetime>='%s' ''' % (start_time)
    results = POSTGRESQLUTILS.select(sql)
    for result in results:
        print(f"patientid: {result[0]}, patientname: {result[1]}, accessnumber: {result[2]}")
    print('-' * 10)
    print(f"The number of newly inserted data is: {len(results)}")
